<?php

namespace app\common\exception;

use think\Exception;
use think\exception\Handle;
use think\facade\Log;
use think\Response;
use Throwable;

/**
 * 应用异常处理类
 */
class ExceptionHandle extends Handle
{
    public $httpStatus = 500;
    private $code;
    private $msg;
    private $errorCode;

    public function render($request, Throwable $e): Response
    {
        if ($e instanceof BaseException) {
            $this->code = $e->code;
            $this->msg = $e->msg;
        } else {
            if (env('APP_DEBUG', false)) {
                return parent::render($request, $e); // 其他错误交给系统处理
            } else {
                $this->code = 1001;
                $this->msg = '404';
                $this->recordErrorLog($e);
            }
        }
        $result = [
            'code' => $this->code,
            'msg'  => $this->msg,
            'status' => 0,
            //  'url' => request()->url()
        ];
        return json($result);
    }
    //记录日志
    public function recordErrorLog($e)
    {
        Log::record($e->getMessage(), 'error');
    }
}
